"use client"


import { Button } from "@/components/ui/button"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import * as z from "zod"
import { toast } from "sonner"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import Link from 'next/link'
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Textarea } from "@/components/ui/textarea"
import { useRouter } from 'next/navigation'
import { trpc } from "@/trpc/client"
const createFormSchema = z.object({
  id: z.union([z.number(), z.undefined()]),
  name: z.string().min(1, {
    message: "不能为空",
  }),
  description: z.string().min(1, {
    message: "不能为空",
  }),
  priority: z.string().min(1, {
    message: "不能为空",
  }),
})

export type createFormSchemaType = z.infer<typeof createFormSchema>;

export default function TaskForm({ task }: { task?: any }) {


  const { mutate: createTask } = trpc.createTasks.create.useMutation({
    onSuccess: () => {
      toast.success("创建成功", {
        description: "恭喜你新增成功了一条task",
        action: {
          label: "去查看",
          onClick: () => {
            // 调用父组件传递的刷新函数
            window.location.href = '/'
          },
        },
      })
    }
  })
  const { mutate: updateTask } = trpc.createTasks.update.useMutation({
    onSuccess: () => {
      // 调用父组件传递的刷新函数
      window.location.href = '/'
    }
  })
  const form = useForm<createFormSchemaType>({
    resolver: zodResolver(createFormSchema),
    defaultValues: {
      id: task?.id,
      name: task?.name,
      description: task?.description as any,
      priority: task?.priority as any,
    }
  })

  async function onSubmit(values: createFormSchemaType) {
    console.log(values, "values")
    if (task?.id) {
      const result = await updateTask({
        id: Number(values.id),
        name: values.name,
        description: values.description,
        priority: values.priority as "low" | "medium" | "high"
      });
      console.log(result, "result update")
    } else {
      const data = await createTask({
        name: values.name,
        description: values.description,
        priority: values.priority as "low" | "medium" | "high"
      })
      console.log(data, "result")
    }
  }

  return (
    <div className='py-[100px] flex justify-center'>
      <Form {...form}>
        <div>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="p-[20px] w-[420px]"
          >

            <Card className="w-[350px]">
              <CardHeader>
                <CardTitle>{task?.id ? 'Update Task' : 'Create Task'}</CardTitle>
                <CardDescription>Fill out the form below to create a new task</CardDescription>
              </CardHeader>
              <CardContent>
                <FormField control={form.control} name="id"
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <Input type="hidden" defaultValue={field.value} {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}>

                </FormField>
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>任务名称</FormLabel>
                      <FormControl>
                        <Input defaultValue={field.value} {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem className='mt-[20px]'>
                      <FormLabel>任务描述</FormLabel>
                      <FormControl>
                        <Textarea id="description" defaultValue={field.value}  {...field} placeholder="description of your project" />
                      </FormControl>
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="priority"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>任务等级</FormLabel>
                      <Select onValueChange={field.onChange} defaultValue={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="Select a verified email to display" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="low">low</SelectItem>
                          <SelectItem value="medium">medium</SelectItem>
                          <SelectItem value="high">high</SelectItem>
                          <SelectItem value="urgent">urgent</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

              </CardContent>
              <CardFooter>
                <div className='flex justify-between mt-[20px]'>
                  {
                    task?.id ? <Button size='lg' className='w-full' type="submit">
                      更新
                    </Button> : <Button size='lg' className='w-full' type="submit">
                      创建
                    </Button>
                  }
                </div>
              </CardFooter>
            </Card>

          </form>
        </div>
      </Form>
    </div>
  )
}
